package home.main.util;

import home.main.entity.Product;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.text.AbstractDocument.BranchElement;

import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.tags.Div;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;


public class SiteReader {
	
	private String siteUrl;
	
	private boolean flag = false;
	
	private URL url;
	private ArrayList<Product> listProducts = new ArrayList<Product>();
	private Parser parser; 
	
	public SiteReader() {
			parser = new Parser();
	}
	
	
	public URL getUrl() {
		return url;
	}

	public void setUrl(String url) {
		try {
			this.url = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}
	
	
	
	public void readDate(List<Product> listProduct){
		
		String URL_QUERI = "http://deuter.com/en_DE/search.php?query=";
		
		try {
			
			System.out.println("Start read data. Count Real size = "+listProduct.size()+"\n");
			
//			listProduct = getMock();
//			System.out.println("Start read data. Count mock size = "+listProduct.size());
			
			int i = 0, j = 0;
			
			for (Product product : listProduct) {
				if(product.getArticle().equals("37142")){
					System.out.println(product);
				}
				System.out.println("Start find Product="+product.getArticle());
				System.out.println("Search URL = "+URL_QUERI+product.getArticle());
				parser.setURL(URL_QUERI+product.getArticle());
				NodeList list = parser.extractAllNodesThatMatch(new NodeClassFilter(LinkTag.class));
				String productURL =  findLinkToProdact(list, product.getArticle());
				if (productURL.isEmpty()) {
					System.out.println("Product="+product.getArticle()+" not FOUND\n");
				}else{
					
					i++;
					System.out.println("\nCCCcount = "+i+"\n");
					
					parser.setURL(productURL);
					NodeList listDiv = parser.extractAllNodesThatMatch(new NodeClassFilter(Div.class));
//					getProductDate(listDiv,product);
					parser.setURL(productURL);
					NodeList listSmallImage = parser.extractAllNodesThatMatch(new NodeClassFilter(ImageTag.class));
					parser.setURL(productURL);
					NodeList listLargeImage = parser.extractAllNodesThatMatch(new NodeClassFilter(LinkTag.class));
					getProductImage(listLargeImage, listSmallImage, product);
					
//					if(i>=10)break;	
					
				}
			
			}
			
		} catch (ParserException e) {
			System.out.println("Ops, can`t read url.");
			e.printStackTrace();
		}
	}
	
	
	private String findLinkToProdact(NodeList listNodeList, String article){
		String productURL = "";
		for (int i = 0; i < listNodeList.size(); i++) {
			String tempURL = listNodeList.elementAt(i).getText();
			if (tempURL.contains(article)) {
				if(tempURL.contains("http://www.deuter.com/en_DE/")){
					System.out.println("________");
					System.out.println(tempURL);
					productURL = tempURL.split("href=\"")[1].replace("#38;", "");
					System.out.println(productURL);
					break;
				}
			}
		}
		return productURL;
		
	}
	
	private void getProductDate(NodeList list, Product product){
		
		for (int i = 0; i < list.size(); i++) {
//			String tempDate = list.elementAt(i).getText();
			
//			System.out.println(list.elementAt(i).getText());
			if (list.elementAt(i).getText().contains("tab1")) {
//				System.out.println(list.elementAt(i).toHtml());
				System.out.println(list.elementAt(i).toHtml(false));
			};
		}
		
	}
	
	private void getProductImage(NodeList listLargeImage, NodeList listSmallImage, Product product){
		
		String imageURLPrefix = "http://www.deuter.com";
		String tempURL = "";
		for (int i = 0; i < listLargeImage.size(); i++) {
			tempURL = listLargeImage.elementAt(i).getText();
			if (tempURL.contains("zoom")) {
				tempURL = imageURLPrefix+tempURL.split("a href=\"")[1].split("\" ")[0];
				System.out.println("+++==+++==+++==="+tempURL);
				break;
			}
		}
	
		saveImage(tempURL,"_large", product);
		
		for (int i = 0; i < listSmallImage.size(); i++) {
			tempURL = listSmallImage.elementAt(i).getText();
			if (tempURL.contains("\"image\"")) {
				tempURL = imageURLPrefix+tempURL.split("img src=\"")[1].split("\" ")[0];
				System.out.println("+++==+++==+++==="+tempURL);
				break;
			}
		}
		saveImage(tempURL, "_small", product);
		
		
		
	}

	
	private boolean saveImage(String image,String suffix, Product product){
		
		try {
		String fileName = "img/"+product.getArticle()+"_"+product.getColorNumber()+suffix+".jpg";
			BufferedImage img = ImageIO.read(new URL(image));
			File file = new File(fileName);
			if (!file.exists()) {
				file.createNewFile();
			}
			ImageIO.write(img, "jpg", file);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("Opse can not save image = "+image);
			e.printStackTrace();
		}
		
		return true;
	}
	
	
	private List<Product> getMock(){
		ArrayList<Product> productList = new ArrayList<Product>();
		Product product = new Product();
		product.setArticle("37142");
		product.setColorNumber("40050");
		product.setColor("titan");
		product.setModel("Second Skin");
		
		Product product2 = new Product();
		product2.setArticle("37061");
		product2.setColorNumber("75001");
		product2.setColor("black-cranberry");
		product2.setModel("Two Face");
		
		Product product3 = new Product();
		product3.setArticle("37071");
		product3.setColorNumber("41001");
		product3.setColor("titan-black");
		product3.setModel("Dream Lite 500");
		
		Product product4 = new Product();
		product4.setArticle("37081");
		product4.setColorNumber("41001");
		product4.setColor("titan-black");
		product4.setModel("Dream Lite 500 L");
		
		productList.add(product);
		productList.add(product2);
		productList.add(product3);
		productList.add(product4);
		
		
		return productList;
		
	}

}
